<template>
  <div class="activity-container">
    <div class="content-wrapper">
      <!-- 搜索区域 -->
      <div class="search-container">
        <div class="search-fields">
          <el-select v-model="searchForm.channel" placeholder="请选择" class="search-select">
            <el-option label="请选择" value=""></el-option>
            <el-option label="线上活动" value="online"></el-option>
            <el-option label="线下活动" value="offline"></el-option>
            <el-option label="推广介绍" value="promotion"></el-option>
          </el-select>
          
          <el-select v-model="searchForm.type" placeholder="请选择" class="search-select">
            <el-option label="请选择" value=""></el-option>
            <el-option label="砸金蛋活动" value="eggBreaking"></el-option>
            <el-option label="锦鲤活动" value="luckyDraw"></el-option>
            <el-option label="转盘抽奖" value="turntable"></el-option>
          </el-select>
          
          <el-select v-model="searchForm.status" placeholder="请选择" class="search-select">
            <el-option label="请选择" value=""></el-option>
            <el-option label="进行中" value="active"></el-option>
            <el-option label="已结束" value="ended"></el-option>
            <el-option label="未开始" value="pending"></el-option>
          </el-select>
        </div>
        
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      
      <!-- 新增按钮 -->
      <div class="action-button">
        <el-button type="primary" @click="showAddDialog">新增活动</el-button>
      </div>
      
      <!-- 活动列表表格 -->
      <div class="table-container">
        <el-table :data="activityList" style="width: 100%">
          <el-table-column prop="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column prop="name" label="活动名称" align="center"></el-table-column>
          <el-table-column prop="channel" label="渠道来源" align="center"></el-table-column>
          <el-table-column prop="activityType" label="活动类型" align="center"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" align="center"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" align="center"></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
              <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 暂无数据提示 -->
        <el-empty v-if="activityList.length === 0" description="暂无数据"></el-empty>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ totalRecords }} 条记录
        </div>
        <div class="pagination-controls">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="prev, pager, next, jumper"
            :total="totalRecords"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <div class="page-size-display">
            {{ pageSize }}条/页
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="活动名称">
          <el-input v-model="formData.name" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="渠道来源">
          <el-select v-model="formData.channel" placeholder="请选择渠道来源">
            <el-option label="线上活动" value="线上活动"></el-option>
            <el-option label="线下活动" value="线下活动"></el-option>
            <el-option label="推广介绍" value="推广介绍"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="formData.activityType" placeholder="请选择活动类型">
            <el-option label="砸金蛋活动" value="砸金蛋活动"></el-option>
            <el-option label="锦鲤活动" value="锦鲤活动"></el-option>
            <el-option label="转盘抽奖" value="转盘抽奖"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'

// API请求基础配置
const API_BASE_URL = '/api'
const API_ENDPOINTS = {
  GET_ACTIVITIES: `${API_BASE_URL}/activities`,
  ADD_ACTIVITY: `${API_BASE_URL}/activities`,
  UPDATE_ACTIVITY: `${API_BASE_URL}/activities`,
  DELETE_ACTIVITY: `${API_BASE_URL}/activities`
}

// 搜索表单
const searchForm = reactive({
  channel: '',
  type: '',
  status: ''
})

// 活动列表数据
const activityList = ref([])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(20)

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增活动')
const formData = reactive({
  name: '',
  channel: '',
  activityType: '',
  startTime: '',
  endTime: ''
})
const editingActivityId = ref(null)

// 获取活动列表
const fetchActivities = async () => {
  try {
    const response = await axios.get(API_ENDPOINTS.GET_ACTIVITIES, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        channel: searchForm.channel,
        type: searchForm.type,
        status: searchForm.status
      }
    })
    
    // 处理响应数据
    activityList.value = response.data.list.map((item, index) => ({
      ...item,
      index: (currentPage.value - 1) * pageSize.value + index + 1
    }))
    totalRecords.value = response.data.total
  } catch (error) {
    console.error('获取活动列表失败:', error)
    // 使用模拟数据
    setMockData()
  }
}

// 设置模拟数据
const setMockData = () => {
  const mockTypes = ['砸金蛋活动', '锦鲤活动', '转盘抽奖']
  const mockChannels = ['线上活动', '线下活动', '推广介绍']
  const mockPrizes = ['20元', '30元', '50元', '100元', '500元']
  
  activityList.value = Array.from({ length: 10 }, (_, index) => {
    const baseDate = new Date()
    const startDate = new Date(baseDate.getTime() - Math.random() * 30 * 24 * 60 * 60 * 1000)
    const endDate = new Date(startDate.getTime() + Math.random() * 30 * 24 * 60 * 60 * 1000)
    
    return {
      id: index + 1,
      index: (currentPage.value - 1) * pageSize.value + index + 1,
      name: `营销大促活动00${index + 1}`,
      channel: mockChannels[index % mockChannels.length],
      activityType: `${mockTypes[index % mockTypes.length]}(${mockPrizes[index % mockPrizes.length]})`,
      startTime: startDate.toISOString().replace('T', ' ').substring(0, 19).replace('.000Z', ''),
      endTime: endDate.toISOString().replace('T', ' ').substring(0, 19).replace('.000Z', '')
    }
  })
  
  totalRecords.value = 20
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchActivities()
}

// 重置搜索
const handleReset = () => {
  searchForm.channel = ''
  searchForm.type = ''
  searchForm.status = ''
  handleSearch()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增活动'
  editingActivityId.value = null
  // 重置表单
  formData.name = ''
  formData.channel = ''
  formData.activityType = ''
  formData.startTime = ''
  formData.endTime = ''
  dialogVisible.value = true
}

// 显示编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑活动'
  editingActivityId.value = row.id
  // 填充表单数据
  formData.name = row.name
  formData.channel = row.channel
  formData.activityType = row.activityType
  formData.startTime = new Date(row.startTime)
  formData.endTime = new Date(row.endTime)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (editingActivityId.value) {
      // 编辑活动
      await axios.put(`${API_ENDPOINTS.UPDATE_ACTIVITY}/${editingActivityId.value}`, formData)
    } else {
      // 新增活动
      await axios.post(API_ENDPOINTS.ADD_ACTIVITY, formData)
    }
    dialogVisible.value = false
    fetchActivities() // 重新获取列表
  } catch (error) {
    console.error('保存活动失败:', error)
    // 模拟成功
    dialogVisible.value = false
    fetchActivities()
  }
}

// 删除活动
const handleDelete = async (row) => {
  try {
    await axios.delete(`${API_ENDPOINTS.DELETE_ACTIVITY}/${row.id}`)
    fetchActivities() // 重新获取列表
  } catch (error) {
    console.error('删除活动失败:', error)
    // 模拟成功
    fetchActivities()
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchActivities()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchActivities()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.activity-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.content-wrapper {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-fields {
  display: flex;
  gap: 16px;
}

.search-select {
  width: 200px;
}

.search-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-info {
  color: #606266;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-size-display {
  color: #606266;
}

.dialog-footer {
  text-align: right;
}
</style>